//
//  JKCountDownButton.swift
//  test-ios
//
//  Created by wyz5204 on 2023/3/2.
//

import UIKit

class JKCountDownButton: UIButton {
    
    private var _touchedCountDownButtonHandler : ((JKCountDownButton,Int) -> Void )? = nil
    private var _countDownChanging : ((JKCountDownButton,Int) ->String)? = nil
    private var _countDownFinished : ((JKCountDownButton,Int) ->String)? = nil
    private var _totalSecond = 0
    private var _second = 0
    private lazy var _startDate :Date? = nil
    private var  _timer : Timer? = nil
    
    func setCountDownButtonHandler(call : @escaping (JKCountDownButton,Int) -> Void){
        self._touchedCountDownButtonHandler = call
        self.addTarget(self, action: #selector(click(sender:)), for: UIControl.Event.touchUpInside)
    }
    
    func setCountDownChanging(call : @escaping ((JKCountDownButton,Int) ->String)){
        self._countDownChanging = call
    }
    
    func setCountDownFinished(call : @escaping ((JKCountDownButton,Int) ->String)){
        self._countDownFinished = call
    }
    
    @objc func click(sender:JKCountDownButton){
        self.makeToast("click")
        if (_touchedCountDownButtonHandler != nil) {
            DispatchQueue.main.async { [self] in
                self._touchedCountDownButtonHandler!(sender , sender.tag)
            }
        }
    }
    
    func startCountDownWithSecond(totalSecond : Int){
        _totalSecond = totalSecond
        _second = totalSecond
        _timer = Timer.scheduledTimer(timeInterval: 1.0, target: JKCountDownButton.self, selector: #selector(JKCountDownButton.blockInvoke(timer:)), userInfo: {
            self.timerStart()
        }, repeats: true)
        _startDate = Date()
        _timer?.fireDate = Date.distantPast
        RunLoop.current.add(_timer!, forMode: RunLoop.Mode.common)
    }
    
    @objc static func blockInvoke(timer: Timer){
        (timer.userInfo as? (()->Void))?()
    }
    
    func timerStart(){
        print("开始计时")
        let deltaTime = Date().timeIntervalSince(_startDate!)
        _second = _totalSecond - Int((deltaTime + 0.5)) ;
        if (_second < 0){
            self.stopCountDown();
        }else{
            if (_countDownChanging != nil)
            {
                DispatchQueue.main.async { [self] in
                    let title = self._countDownChanging!(self , _second)
                    self.setTitle(title, for: UIControl.State.normal)
                    self.setTitle(title, for: UIControl.State.disabled)
                }
            }
            else
            {
                let title = String.init(format: "%zd秒", _second)
                self.setTitle(title, for: UIControl.State.normal)
                self.setTitle(title, for: UIControl.State.disabled)
            }
        }
    }
    
    func stopCountDown(){
        if(_timer?.responds(to: #selector(getter: Timer.isValid)) ?? false){
            if(_timer?.isValid ?? false){
                _timer?.invalidate()
                
                _second = _totalSecond;
                
                if(_countDownFinished != nil) {
                    DispatchQueue.main.async { [self] in
                        let title = self._countDownFinished!(self ,_totalSecond)
                        self.setTitle(title, for: UIControl.State.normal)
                        self.setTitle(title, for: UIControl.State.disabled)
                    }
                }else {
                    self.setTitle("重新获取", for: UIControl.State.normal)
                    self.setTitle("重新获取", for: UIControl.State.disabled)
                }
            }
        }
    }
}
